import { getFullPath } from './index'

export const http = (options: any) => {
	let token = uni.getStorageSync('token')

	if (token) {
		options.header = {
			Authorization: token,
		}
	}

	// 1. 返回 Promise 对象
	return new Promise((resolve, reject) => {
		uni.request({
			header: options.header,
			url: options.url,
			data: options.data,
			method: options.method,
			query: { ...options.query },
			// 响应成功
			success(res: any) {
				if (res.statusCode == 200) {
					if (res.data.code == 200 || res.data.code == 300) {
						resolve(res.data)
					} else if (res.data.code == 105) {
						resolve(res.data)
					} else if (res.data.code == 220) {
						uni.navigateTo({ url: '/pages/code/index' })
						resolve(res.data)
					} else if (res.data.code == -1) {
						// 获取当前页 保存到storage中
						let route = getFullPath()
						uni.setStorageSync('backRoute', route)
						// 未登录
						uni.redirectTo({ url: '/pages/login/index' })
					} else if (res.data.code == -2) {
						// 获取当前页 保存到storage中
						let route = getFullPath()
						uni.setStorageSync('backRoute', route)
						// 未登录
						uni.reLaunch({ url: '/pages/process/index' })
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg,
						})
						reject(res)
					}
				} else {
					// 其他错误 -> 根据后端错误信息轻提示
					!options.hideErrorToast &&
						uni.showToast({
							icon: 'none',
							title: res.data.msg,
						})
					reject(res)
				}
			},
			// 响应失败
			fail(err) {
				uni.showToast({
					icon: 'none',
					title: '网络异常',
				})
				reject(err)
			},
		})
	})
}

/**
 * GET 请求
 * @param url 后台地址
 * @param query 请求query参数
 * @returns
 */
export const httpGet = (url: string, query?: any) => {
	return http({
		url,
		query,
		method: 'GET',
	})
}

/**
 * POST 请求
 * @param url 后台地址
 * @param data 请求body参数
 * @param query 请求query参数，post请求也支持query，很多微信接口都需要
 * @returns
 */
export const httpPost = (url: string, data?: any, query?: any) => {
	return http({
		url,
		query,
		data,
		method: 'POST',
	})
}

http.get = httpGet
http.post = httpPost
